package com.tdkj.service.shop.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.tdkj.dao.shop.IBeanGoodAuctionQuoteDao;
import com.tdkj.model.shop.BeanGood;
import com.tdkj.model.shop.BeanGoodAuction;
import com.tdkj.model.shop.BeanGoodAuctionQuote;
import com.tdkj.model.user.BeanUser;
import com.tdkj.service.BaseService;
import com.tdkj.service.shop.IBeanGoodAuctionQuoteService;
@Component("goodAuctionQuoteService")
public class BeanGoodAuctionQuoteServiceImpl extends BaseService implements
		IBeanGoodAuctionQuoteService {
	
	private  IBeanGoodAuctionQuoteDao beanGoodAuctionQuoteDao;
    
	@Resource
	public void setBeanGoodAuctionQuoteDao(IBeanGoodAuctionQuoteDao beanGoodAuctionQuoteDao) {
		this.beanGoodAuctionQuoteDao = beanGoodAuctionQuoteDao;
	}

	@Override
	public List<BeanGoodAuctionQuote> getQuotes(Long userId) {
		BeanUser user = beanGoodAuctionQuoteDao.findById(userId, BeanUser.class);
		return beanGoodAuctionQuoteDao.findByProperty("user", user, BeanGoodAuctionQuote.class, "quoteTime", "desc");
	}
	
	@Override
	public List<BeanGoodAuctionQuote> getQuotes(Long userId, String state) {
		return beanGoodAuctionQuoteDao.getSession().createQuery("from " + BeanGoodAuctionQuote.class.getName() + " bean where bean.user.id="+userId+" and bean.auction.state='"+state+"'").list();
	}

	@Override
	public BeanGoodAuctionQuote add(Long goodId, Long userId) {
		BeanUser user = beanGoodAuctionQuoteDao.findById(userId, BeanUser.class);
		BeanGood good = beanGoodAuctionQuoteDao.findById(goodId, BeanGood.class);
		BeanGoodAuction auction = good.getCurrentAuction();
		
		BeanGoodAuctionQuote quote = new BeanGoodAuctionQuote();
		quote.setAuction(auction);
		if(auction.getFinalQuote()==null){
			quote.setPrice(good.getPrice().add(good.getRateOfIncrease()));
		}else{
			quote.setPrice(auction.getFinalQuote().getPrice().add(good.getRateOfIncrease()));
		}
		
		quote.setQuoteTime(new Timestamp(System.currentTimeMillis()));
		quote.setUser(user);
		
		beanGoodAuctionQuoteDao.save(quote);
		
		auction.setFinalQuote(quote);
		
		return quote;
	}

}
